package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.dao.MemberDao;
import com.itheima.pojo.Member;
import com.itheima.pojo.OrderDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.Date;

@RestController
@RequestMapping("/member")
@Slf4j
public class MemberController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberDao memberDao;

    /**
     * 用户登录
     * @param orderDTO
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody OrderDTO orderDTO){
        log.info("用户登录:{}", orderDTO.toString());
        String code = (String)redisTemplate.opsForValue().get(RedisMessageConstant.SENDTYPE_LOGIN + "-" + orderDTO.getTelephone());
        //验证码有没有过期
        if(code == null || code.equals("")){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //验证码是否一致
        if(!orderDTO.getValidateCode().equals(code)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        Member member = memberDao.getByTelephone(orderDTO.getTelephone());
        if(member == null){
            // 注册会员
            member = new Member();
            member.setRegTime(new Date());
            member.setPhoneNumber(orderDTO.getTelephone());
            memberDao.insert(member);
        }
        return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }
}
